<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\AdminBaseController;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\portal\model\PortalCategoryModel;
use think\Db;
use app\admin\model\ThemeModel;

use app\portal\model\HouseFieldType;
use app\portal\model\HouseFieldTypeCategory;
use app\portal\model\House;
use app\portal\model\HouseData;
use app\portal\model\HousePassword;
use app\portal\model\UserHousePasswordModel;
use app\portal\model\UserFavoriteModel;

class AdminHouseController extends AdminBaseController
{

    public function default () {
    }

    public function index ()
    {
        $param = $this->request->param();
        $keyword = '';
        if (isset($param['keyword']) && !empty($param['keyword'])) {
          $keyword = $param['keyword'];
          $list = House::with('count')->where('title', 'like', "%{$keyword}%")->orderRaw('id desc')->paginate(10, false, ['query' => request()->param()]);
        } else {
          $list = House::orderRaw('id desc')->paginate(10);
        }

        // 获取参数
        $fieldIds = [];
        foreach ($list as $key => $value) {
          if (!isset($fieldIds[$value->structure_type])) {
            $fieldIds[$value->structure_type] = $value->structure_type;
          }

          if (!isset($fieldIds[$value->decoration_type])) {
            $fieldIds[$value->decoration_type] = $value->decoration_type;
          }

          if (!isset($fieldIds[$value->direction])) {
            $fieldIds[$value->direction] = $value->direction;
          }

        }

        $paramsData = HouseFieldType::whereIn('id', $fieldIds)->select();
        $params = [];
        foreach ($paramsData as $key => $value) {
          $params[$value->id] = $value->name;
        }

        $this->assign('keyword', $keyword);
        $this->assign('list', $list);
        $this->assign('params', $params);
        return $this->fetch();
    }

    /* 添加房源页面 */
    public function add ()
    {
      $params = HouseFieldType::with('param')->select();
      $selectData = [];
      foreach ($params as $key => $value) {
        $selectData[$value->catid][$value->id] = $value->name;
      }

      $selectData['myself'] = [
        ['name' => '优居房源', 'value' => '1'],
        ['name' => '非优居美化房源', 'value' => '3'],
        ['name' => '非美化房源', 'value' => '2'],
      ];

      $this->assign('selectData', $selectData);

      return $this->fetch();
    }

    // 添加房源操作
    public function addForm()
    {
        if (!$this->request->isPost()) {
          return $this->error('Forbidden', 403);
        }

        $param = $this->request->param();
        $post = $param['post'];

        // 验证
        $result = $this->validate($post, 'House');
        if ($result !== true) {
            $this->error($result);
        }

        if (!isset($param['slide_urls']) || empty($param['slide_urls']) || !isset($param['slide_names']) || empty($param['slide_names'])) {
          $this->error('请设置展示图片！');
        }

        $date = date('Y-m-d H:i:s');
        $house = new House;
        $house->password = $post['password'];
        $house->sell_type = $post['sell_type'];
        $house->myself = $post['myself'];

        $house->title = $post['title'];
        $house->keywords = $post['keywords'];
        $house->thumb = $post['thumb'];

        $house->price = $post['price'];
        $house->univalent = $post['univalent'];

        $house->acreage = $post['acreage'];
        $house->structure_type = $post['structure_type'];
        $house->decoration_type = $post['decoration_type'];
        $house->direction = $post['direction'];
        $house->purpose = $post['purpose'];

        $house->estate_name = $post['estate_name'];
        $house->address = $post['address'];
        $house->region = $post['region'];
        $house->position = $post['position'];

        $house->years = $post['years'];
        $house->property_year = $post['property_year'];

        $house->floor = $post['floor'];
        $house->top_floor = $post['floorall'];
        $house->floor_type = $post['floor_type'];

        $house->two_tax = $post['two_tax'];
        $house->tax_bear_type = $post['tax_bear_type'];
        $house->arrears = !isset($post['arrears']) || empty($post['arrears']) ? $post['arrears'] : -1;
        $house->hukou = !isset($post['hukou']) || empty($post['hukou']) ? $post['hukou'] : -1;
        $house->daikanshijian = $post['daikanshijian'];
        $house->daofang = $post['daofang'];
        $house->qitashuoming = $post['qitashuoming'];

        $house->reward = $post['reward'];
        $house->contact = $post['contact']; // 联系电话
        $house->video_address = $post['video_address'];
        $house->created_at = $date;
        $house->update_at = $date;
        $ok = $house->save();

        if (!$ok) {
          $this->error('未知错误，添加失败！');
        }

        $houseData = new HouseData;

        // 展示图片数据转换
        $slides = [];
        foreach ($param['slide_names'] as $key => $name) {
          $slides[] = [
            'url' => $param['slide_urls'][$key],
            'name' => $name,
          ];
        }

        // 位置图片数据转换
        $position_pictures = [];
        if (isset($param['picture_names']) && !empty($param['picture_names'])) {
          foreach ($param['picture_names'] as $key => $name) {
            $position_pictures[] = [
              'url' => $param['picture_urls'][$key],
              'name' => $name,
            ];
          }
        }

        $content = '';
        if (isset($post['content']) && !empty($post['content'])) {
          $content = $post['content'];
        }

        $houseData->house_id = $house->id;
        $houseData->content = $content;
        $houseData->process = $post['process'];
        $houseData->slides = $slides;
        $houseData->position_picture = $position_pictures;
        $houseData->save();

        $this->success('房源添加成功');
    }

    public function edit()
    {
      $param = $this->request->param();
      $id = $param['id'];

      // 获取选项数据
      $params = HouseFieldType::with('param')->select();
      $selectData = [];
      foreach ($params as $key => $value) {
        $selectData[$value->catid][$value->id] = $value->name;
      }

      // 获取数据
      $houseModel = new House;
      $data = House::get($id);
      $data['keywords'] = $data->getData('keywords');
      // content html转义
      $data->profile->content = htmlspecialchars_decode($data->profile->content);

      // 自营
      $selectData['myself'] = [
        ['name' => '优居房源', 'value' => '1'],
        ['name' => '非优居美化房源', 'value' => '3'],
        ['name' => '非美化房源', 'value' => '2'],
      ];

      // 出售情况
      $selectData['sell_type'] = [
        ['name' => '在售', 'value' => '1'],
        ['name' => '即售', 'value' => '2'],
        ['name' => '预售', 'value' => '3'],
        ['name' => '已售', 'value' => '4'],
      ];

      // 密码
      $selectData['password'] = [
        ['name' => '是', 'value' => '1'],
        ['name' => '否', 'value' => '0'],
      ];

      // 解析楼层信息
      $this->assign('data', $data);
      $this->assign('selectData', $selectData);

      return $this->fetch();
    }

    public function editForm()
    {
      if (!$this->request->isPost()) {
        return $this->error('Forbidden', 403);
      }

      $param = $this->request->param();
      if (!isset($param['post']['id'])) {
        $this->error('非法参数！');
      }
      $id = $param['post']['id'];
      $post = $param['post'];

      // 验证
      $result = $this->validate($post, 'House');
      if ($result !== true) {
          $this->error($result);
      }

      if (!isset($param['slide_urls']) || empty($param['slide_urls']) || !isset($param['slide_names']) || empty($param['slide_names'])) {
        $this->error('请设置展示图片！');
      }

      $house = House::get($id);
      $house->password = $post['password'];
      $house->sell_type = $post['sell_type'];
      $house->myself = $post['myself'];

      $house->title = $post['title'];
      $house->keywords = $post['keywords'];
      $house->thumb = $post['thumb'];

      $house->price = $post['price'];
      $house->univalent = $post['univalent'];

      $house->acreage = $post['acreage'];
      $house->structure_type = $post['structure_type'];
      $house->decoration_type = $post['decoration_type'];
      $house->direction = $post['direction'];
      $house->purpose = $post['purpose'];

      $house->estate_name = $post['estate_name'];
      $house->address = $post['address'];
      $house->position = $post['position'];

      $house->years = $post['years'];
      $house->property_year = $post['property_year'];

      $house->floor = $post['floor'] . '/' . $post['floorall'];
      $house->floor_type = $post['floor_type'];

      $house->two_tax = $post['two_tax'];
      $house->tax_bear_type = $post['tax_bear_type'];
      $house->arrears = !isset($post['arrears']) || empty($post['arrears']) ? $post['arrears'] : -1;
      $house->hukou = !isset($post['hukou']) || empty($post['hukou']) ? $post['hukou'] : -1;
      $house->daikanshijian = $post['daikanshijian'];
      $house->daofang = $post['daofang'];
      $house->qitashuoming = $post['qitashuoming'];

      $house->reward = $post['reward'];

      $house->contact = $post['contact']; // 咨询电话

      $house->video_address = $post['video_address'];
      $house->update_at = date('Y-m-d H:i:s');
      $house->save();

      $houseData = new HouseData;

      // 展示图片数据转换
      $slides = [];
      foreach ($param['slide_names'] as $key => $name) {
        $slides[] = [
          'url' => $param['slide_urls'][$key],
          'name' => $name,
        ];
      }

      // 位置图片数据转换
      $position_pictures = [];
      if (isset($param['picture_names']) && !empty($param['picture_names'])) {
        foreach ($param['picture_names'] as $key => $name) {
          $position_pictures[] = [
            'url' => $param['picture_urls'][$key],
            'name' => $name,
          ];
        }
      }

      $houseData->save([
          'content'  => $post['content'],
          'process'  => $post['process'],
          'slides' => $slides,
          'position_picture' => $position_pictures,
      ],['house_id' => $house->id]);

      $this->success('房源修改成功');
    }

    public function delete()
    {
        $param           = $this->request->param();
        if (!isset($param['id'])) {
          $this->error('参数不正确！');
        }

        $house = House::get($param['id']);
        if (empty($house)) {
          $this->error('数据已删除');
        }

        Db::startTrans();

        try{
          UserFavoriteModel::where('object_id', $param['id'])->delete();
          UserHousePasswordModel::where('house_id', $param['id'])->delete();
          HousePassword::where('house_id', $param['id'])->delete();
          $res = $house->together(['profile'])->delete();
        } catch (\Exception $e) {
          // 回滚事务
          Db::rollback();
          $this->error('删除失败');
        }

        Db::commit();
        $this->success('删除房源成功！');
    }

    public function delete_all () {
      $param = $this->request->param();
      if (!isset($param['ids']) || empty($param['ids'])) {
        $this->error('参数错误！');
      }
      House::destroy($param['ids']);
      $this->success('删除成功');
    }

}
